import random

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
import time
import os
import requests
import json
import re

from bs4 import BeautifulSoup


def start_web(chrome_driver_path, url):
    # 配置Chrome选项
    options = Options()
    # 如果不需要显示浏览器界面，可以添加这个选项
    options.add_argument('--headless')
    options.add_argument('--disable-gpu')

    # 启动WebDriver
    service = Service(chrome_driver_path)
    driver = webdriver.Chrome(service=service, options=options)

    # 打开网页

    driver.get(url)

    # 等待页面加载
    time.sleep(5)

    # 模拟下拉加载，滚动到底部
    last_height = driver.execute_script("return document.body.scrollHeight")
    while True:
        # 滚动到底部
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(2)  # 等待加载
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:  # 如果没有新内容加载
            break
        last_height = new_height
    time.sleep(5)
    # 获取页面的 HTML
    html = driver.page_source

    # 使用 BeautifulSoup 解析 HTML
    soup = BeautifulSoup(html, 'html.parser')

    # a_elements = soup.find_elements(By.CSS_SELECTOR, "#pic-content > div.flex.flex-wrap a")
    a_elements = soup.select('#pic-content > div.flex.flex-wrap a')

    list_url = []
    dist_url = {}
    print(len(a_elements))
    for a in a_elements:
        href = a.get("href")
        a_span = a.select("div.bottom-warp > span")
        title = a_span[0].get("title")
        if href:
            # print(f"title={title} ,href={href}")
            list_url.append(href)
            dist_url[href] = title
    # 关闭浏览器
    driver.quit()
    return list_url, dist_url


def get_links_from_page(chrome_driver_path, url):
    # 配置Chrome选项
    options = Options()
    options.add_argument('--headless')  # 如果不需要显示浏览器界面，可以添加这个选项
    options.add_argument('--disable-gpu')

    # 启动WebDriver
    service = Service(chrome_driver_path)
    driver = webdriver.Chrome(service=service, options=options)

    # 打开网页
    driver.get(url)

    # 等待页面加载
    time.sleep(5)

    # 获取所有 li 元素下的 a 标签的 href 属性
    li_elements = driver.find_elements(By.CSS_SELECTOR,
                                       "#__nuxt > div > div > div.img-list-container > div.img-main > div > div.img-content > section:nth-child(1) > ul > li")

    links = []
    for li in li_elements:
        a_tag = li.find_element(By.TAG_NAME, "a")
        href = a_tag.get_attribute("href")
        if href:
            links.append(href)

    # 关闭浏览器
    driver.quit()
    return links


def post_request(serialGroupId, pageSize):
    # 请求的URL
    url = "https://model-gateway.pcauto.com.cn/library/gallery/photo/terminal/list"

    # 请求的参数
    payload = {
        "serialGroupId": serialGroupId,  # 动态传入 serialGroupId
        "modelId": 0,
        "cateId": 300,
        "subCateId": 0,
        "pageNo": 1,
        "pageSize": pageSize,  # 动态传入 pageSize
        "source": 1,
        "index": 0
    }

    # 设置请求头（如果需要的话，可以添加更多的头信息）
    headers = {
        "Content-Type": "application/json"  # 表示发送的内容是 JSON 格式
    }

    # 发送POST请求
    response = requests.post(url, json=payload, headers=headers)
    print(f'请求参数 = {payload}')
    # 打印返回的数据
    if response.status_code == 200:
        # print("Response Data:")
        # print(json.dumps(response.json(), indent=4))  # 格式化打印返回的JSON数据
        return response.json()  # 返回解析后的 JSON 数据
    else:
        print(f"Request failed with status code: {response.status_code}")


def handlerUrl(url):
    # https: // price.pcauto.com.cn / cars / sg30412 - 300 /  # ad=21981
    if url is None:
        return None
    else:
        # 正则表达式用于匹配sg和-之间的数字
        match = re.search(r'sg(\d+)-', url)
        # 如果找到匹配的数字，返回数字，否则返回None
        if match:
            print(f"url= {url} ")
            return match.group(1)
        else:
            return None


def download_image(image_url, save_path):
    # 检查文件夹是否存在，不存在则创建
    folder = os.path.dirname(save_path)
    if not os.path.exists(folder):
        os.makedirs(folder)

    # 发送 GET 请求下载图片
    response = requests.get(image_url)

    # 检查请求是否成功
    if response.status_code == 200:
        with open(save_path, 'wb') as file:
            file.write(response.content)
        print(f"图片已下载到 {save_path}")
    else:
        print(f"图片下载失败，状态码: {response.status_code}")


def handlerRespose(json_response):
    if type(json_response) is dict:
        path_url = []
        items = json_response.get('data', {}).get('pageResult', [])
        for e in items:
            if e.get('czName') == "2025上海车展":
                path_url.append(e.get('path'))
        return path_url
    else:
        return None


if __name__ == '__main__':
    # 保存路径
    save_path = "D:\\car\\"

    # serialGroupId_input = 28281  # 动态传入的 serialGroupId
    # pageSize_input = 80  # 动态传入的 pageSize
    # json=post_request(serialGroupId_input,pageSize_input)
    # path_url=handlerRespose(json)
    # if path_url is None:
    #     print("path url is null")
    # else:
    #     for e in path_url:
    #         file_name = os.path.basename(e)
    #         real_path=save_path+"car 01"+"\\"+file_name
    #         # 调用函数下载图片
    #         download_image(e, real_path)

    url = "https://price.pcauto.com.cn/pic/chezhan/c49863/#ad=21981"
    chrome_driver_path = "D:\\chromedriver-win64\\chromedriver.exe"
    list_url, dist_url = start_web(chrome_driver_path, url)
    for e in list_url:
        car_name = dist_url[e]
        car_id = handlerUrl(e)
        print(f"car_id = {car_id}, car_name={car_name}")
        serialGroupId_input = car_id  # 动态传入的 serialGroupId
        pageSize_input = 200
        json = post_request(serialGroupId_input, pageSize_input)
        path_url = handlerRespose(json)
        if path_url is None:
            print("path url is null")
        else:
            real_path = save_path + car_name + "_" + str(random.randint(1000, 9999)) + "_\\"
            for e in path_url:
                file_name = os.path.basename(e)
                file_real_path = real_path + file_name
                print(f'real_path={file_real_path}  url={e}')
                # 调用函数下载图片
                download_image(e, file_real_path)
